package com.itsv.cyzx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;





import com.itsv.xhyy.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class LoadImageAysnc2 {

	// 图片缓存软引用
	private HashMap<String, SoftReference<Drawable>> imageCache;
	// 线程池
	private BlockingQueue<Runnable> queue;
	private ThreadPoolExecutor executor;
	private FileOperator fileOperator;
	private Context context;
	private String SDPATH = Environment.getExternalStorageDirectory() + "/";

	public LoadImageAysnc2(Context context) {

		imageCache = new HashMap<String, SoftReference<Drawable>>();
		fileOperator = new FileOperator();
		queue = new LinkedBlockingQueue<Runnable>();
		executor = new ThreadPoolExecutor(1, 5, 180, TimeUnit.SECONDS, queue);
		this.context = context;

	}

	// 异步加载图片的方法（其实可以以任何形式得到图片）
	public Drawable loadImage(final String id, final String wangluoSrc,
			final String bendiSrc, final ImageCallBack imageCallBack) {
		// 如果有缓存则使用缓存中的图片
		if (imageCache.containsKey(id)) {
			SoftReference<Drawable> softReference = imageCache.get(id);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				System.out.println("缓存数据");
				return drawable;
			}
		}
		// 图片加载完成
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Drawable drawable = (Drawable) msg.obj;
				// 图片加载完成的回调函数，用于更新imageview
				imageCallBack.imageLoaded(drawable, wangluoSrc);
			}
		};
		Drawable drawable = null;
		File file = new File(SDPATH + "wh/" + bendiSrc);
		Bitmap b = decodeFile(file);
		if (b != null) {
			drawable = new BitmapDrawable(b);// 如果本地有图片则直接读取
			if (!b.isRecycled()) {
//				b.recycle(); // 回收图片所占的内存
				b = null;
				System.gc(); // 提醒系统及时回收
			}
		}
		if (drawable == null) {
			// 异步图片下载方法
			executor.execute(new Runnable() {

				@Override
				public void run() {

					Drawable drawable = null;
					if (drawable == null) {
						try {
							drawable = getBitmap(wangluoSrc, id);
						} catch (Exception e) {
							BitmapDrawable bd = new BitmapDrawable(
									BitmapFactory.decodeResource(
											context.getResources(),
											R.drawable.cach));
							drawable = (Drawable) bd;
							e.printStackTrace();
						}
					}
					imageCache.put(id, new SoftReference<Drawable>(drawable));
					Message msg = handler.obtainMessage(0, drawable);
					msg.sendToTarget();

				}
			});
		} else {
			imageCache.put(id, new SoftReference<Drawable>(drawable));
			Message msg = handler.obtainMessage(0, drawable);
			msg.sendToTarget();
		}

		return drawable;
	}

	public Drawable getBitmap(String url, String id) {

		// from web
		try {
			Bitmap bitmap = null;

			HttpGet httpRequest = new HttpGet(url);
			HttpResponse response = new DefaultHttpClient()
					.execute(httpRequest);
			HttpEntity entity = response.getEntity();
			BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
					entity);
			InputStream is = bufferedHttpEntity.getContent();
			File file = null;
			fileOperator.creatSDDir("wh/");
			file = fileOperator.creatSDFile("wh/" + id + ".jpg");
			OutputStream os = new FileOutputStream(file);
			StreamTool.CopyStream(is, os);
			is.close();
			os.close();
			bitmap = decodeFile(file);
			Drawable drawable = null;
			if (bitmap != null) {
				drawable = new BitmapDrawable(bitmap);
				if (!bitmap.isRecycled()) {
//					bitmap.recycle(); // 回收图片所占的内存
					bitmap = null;
					System.gc(); // 提醒系统及时回收
				}
			}
			return drawable;
		} catch (Exception ex) {
			ex.printStackTrace();
			BitmapDrawable bd = new BitmapDrawable(
					BitmapFactory.decodeResource(context.getResources(),
							R.drawable.cach));
			return (Drawable) bd;
		}
	}

	// decodes image and scales it to reduce memory consumption
	public Bitmap decodeFile(File f) {
		Bitmap bitmap = null;
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 400;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 8;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null,
					o2);
			return bitmap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	// 回调接口
	public interface ImageCallBack {
		public void imageLoaded(Drawable drawable, String iconSrc);
	}
}
